<?php

namespace home\models;

use yii\base\Model;
use Yii;

/**
 * Signup form
 *
 * @property $username
 * @property $vcode
 * @property $password
 */
class SignupForm extends Model
{
    public $username;
    public $vcode;
    public $password;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required', 'message' => '请输入账号'],
            ['username', 'unique', 'targetClass' => '\home\models\Users', 'message' => '手机号码已注册。'],
            ['username', 'match', 'pattern' => '/^1[3-9][0-9]{9}$/'],

            ['vcode', 'trim'],
            ['vcode', 'required', 'message' => '请输入验证码'],

            ['password', 'required', 'message' => '请输入密码'],
            ['password', 'string', 'min' => 6],
        ];
    }

    public function attributeLabels()
    {
        return [
            'username' => '手机号码',
            'vcode' => '验证码',
            'password' => '密码',
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if(!$this->validate()){
            return NULL;
        }

        $vcode = Yii::$app->cache->get('api_vcode_' . $this->username);
        if($vcode != $this->vcode){
            $this->addError('vcode', '验证码错误！');
            return NULL;
        }

        Yii::$app->cache->delete('api_vcode_' . $this->username);

        $user = new Users();
        $user->username = $this->username;
        $user->mobile = $this->username;
        $user->setPassword($this->password);
        $user->generateAuthKey();

        if(!$user->save()){
            return null;
        }

        return $user;
    }
}
